<template>
    <div class="container">
        <div class="btn-container">
            <el-button @click="goBack">返回上一级</el-button>
        </div>
        <div class="card-container">
            <div class="tab">基本信息</div>
            <el-form :model="form" :inline="true" class="demo-form-inline">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="姓名" required>
                            <el-input v-model="form.patientName" placeholder="请输入姓名" style="width: 180px" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="手机号" required>
                            <el-input v-model="form.phone" placeholder="请输入手机号" style="width: 112px" />
                            <span @click="generateRandom" class="random">随机创建</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="身份证号">
                            <el-input v-model="form.idCard" placeholder="请输入身份证号" style="width: 180px" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="性别" required>
                            <el-radio-group v-model="form.gender" class="ml-4">
                                <el-radio value=1>男</el-radio>
                                <el-radio value=2> 女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="出生日期" required>
                            <el-date-picker v-model="form.birth" type="date" placeholder="出生日期" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" style="width: 150px" :disabled-date="disabledDate"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="文化程度" required>
                            <el-select v-model="form.education" placeholder='请选择'>
                                <el-option v-for="item in educationData" :label="item.label" :value="item.value"
                                    :key="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="民族">
                            <el-select v-model="form.ethnicGroup" placeholder='请选择' style="width: 210px">
                                <el-option v-for="item in ethnicGroupData" :label="item.label" :value="item.value"
                                    :key="item.label" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="血型">
                            <el-select v-model="form.bloodType" placeholder='请选择' style="width: 170px">
                                <el-option v-for="item in bloodTypeData" :label="item.label" :value="item.value"
                                    :key="item.label" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="门诊号">
                            <el-input v-model="form.clinicNumber" placeholder="请输入门诊号" style="width: 175px" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="婚姻状况">
                            <el-select v-model="form.maritalStatus" placeholder='请选择' style="width: 174px">
                                <el-option v-for="item in maritalStatusData" :label="item.label" :value="item.value"
                                    :key="item.label" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="职业">
                            <el-select v-model="form.occupation" placeholder='请选择' style="width: 210px">
                                <el-option v-for="item in occupationData" :label="item.label" :value="item.value"
                                    :key="item.label" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="医院" required>
                            <el-select v-model="form.hospitalId">
                                <el-option v-for="item in hospitalData" :label="item.hospitalName" :value="item.id"
                                    :key="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="card-container" style="margin-top:20px;">
            <div class="tab">健康信息</div>
            <el-form :model="healthForm" class="demo-form-inline">
                <el-form-item label="过敏史">
                    <el-checkbox-group v-model="healthForm.allergyHistory">
                        <el-checkbox v-for="item in allergyHistoryData" :label="item.name" :checked="item.checked"
                            :disabled="isAllergyItemDisabled(item)" :key="item.name" @change="checkChange" />
                    </el-checkbox-group>
                    <el-input type="textarea" :rows="3" v-model="allergyRemark" v-if="allergyHistoryFlag"
                        placeholder="请输入具体过敏药物名称" />
                </el-form-item>
                <el-form-item label="暴露史">
                    <el-checkbox-group v-model="healthForm.exposureHistory">
                        <el-checkbox v-for="item in exposureHistoryData" :label="item.name" :checked="item.checked"
                            :disabled="isExposureItemDisabled(item)" :key="item.name" />
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="既往史">
                    <el-checkbox-group v-model="healthForm.pastHistory">
                        <el-checkbox v-for="item in pastHistoryData" :label="item.name" :checked="item.checked"
                            :disabled="isPastItemDisabled(item)" :key="item.name" />
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="家族史">
                    <el-radio-group v-model="healthForm.familyHistory" class="ml-4">
                        <el-radio v-for="item in familyHistoryData" :label="item.name" :checked="item.checked"
                            @change="radioChange" :key="item.name" />
                    </el-radio-group>
                    <el-input type="textarea" :rows="3" v-model="familyRemark" v-if="familyHistoryFlag"
                        placeholder="请输入家庭成员的具体疾病史" />
                </el-form-item>
                <el-form-item label="遗传病史">
                    <el-radio-group v-model="healthForm.geneticHistory" class="ml-4">
                        <el-radio v-for="item in geneticHistoryData" :label="item.name" :checked="item.checked"
                            @change="radioChange" :key="item.name" />
                    </el-radio-group>
                    <el-input type="textarea" :rows="3" v-model="geneticRemark" v-if="geneticHistoryFlag"
                        placeholder="请输入具体遗传病史" />
                </el-form-item>
                <el-form-item label="残疾情况">
                    <el-checkbox-group v-model="healthForm.disabilityHistory">
                        <el-checkbox v-for="item in disabilityHistoryData" :label="item.name" :checked="item.checked"
                            @change="checkChange" :disabled="isDisabilityItemDisabled(item)" :key="item.name" />
                    </el-checkbox-group>
                    <el-input type="textarea" :rows="3" v-model="disabilityRemark" v-if="disabilityHistoryFlag"
                        placeholder="请输入具体残疾情况" />
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" :rows="3" v-model=healthForm.remark />
                </el-form-item>
            </el-form>
            <div class="bottom-btn">
                <el-button class="save" @click="save">保存</el-button>
                <el-button class="cancel" @click="cancel">取消</el-button>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
    import { ref, reactive,  computed, onMounted } from 'vue'
    import { useRouter } from 'vue-router'
    import { useStore } from 'vuex'
    import { getHospitalList, addPatient } from '@/api/patient/index'
    import { useCheckEmpty } from '@/utils/checkEmpty'
    import { checkIdCard } from '@/utils/checkId'
    import {IHospitalResponse} from '@/types/api'
    import {IHospitalResultType} from '@/types/patient'
    import { ElMessage } from 'element-plus'
    const store = useStore()
    const router = useRouter();
    const disabledDate=(time:Date)=>{
        return time.getTime() > Date.now(); 
    }
    const generateRandom = () => {
    let phoneNumber = '1';
    phoneNumber += [3, 4, 5, 7, 8][Math.floor(Math.random() * 5)];
    for (let i = 0; i < 9; i++) {
        phoneNumber += Math.floor(Math.random() * 10);
    }
    form.phone = phoneNumber
}
    //基本信息下拉框数据
    const educationData = reactive([
        {
            value: 0,
            label: '小学'
        },
        {
            value: 1,
            label: '初中'
        },
        {
            value: 2,
            label: '高中'
        },
        {
            value: 3,
            label: '专科'
        },
        {
            value: 4,
            label: '本科'
        },
        {
            value: 5,
            label: '硕士及以上'
        },
        {
            value: 6,
            label: '其他'
        }
    ])
    const ethnicGroupData = reactive([
        {
            value: 0,
            label: '汉族'
        },
        {
            value: 1,
            label: '少数民族'
        },

    ])
    const bloodTypeData = reactive([
        {
            value: 0,
            label: 'A型'
        },
        {
            value: 1,
            label: 'B型'
        },
        {
            value: 2,
            label: 'O型'
        },
        {
            value: 3,
            label: 'AB型'
        },
        {
            value: 4,
            label: 'RH阴性'
        },
        {
            value: 5,
            label: 'RH阳性'
        },
        {
            value: 6,
            label: 'RH不详'
        },
        {
            value: 6,
            label: '不详'
        }
    ])
    const maritalStatusData = reactive([
        {
            value: 0,
            label: '已婚'
        },
        {
            value: 1,
            label: '未婚'
        },
        {
            value: 2,
            label: '丧偶'
        },
        {
            value: 3,
            label: '离婚'
        },
        {
            value: 4,
            label: '未说明的婚姻状态'
        },
    ])
    const occupationData = reactive([
        {
            value: 0,
            label: '国家机关、党群组织、企业、事业单位负责人'
        },
        {
            value: 1,
            label: '专业技术人员'
        },
        {
            value: 2,
            label: '办事人员和有关人员'
        },
        {
            value: 3,
            label: '商业、服务业人员'
        },
        {
            value: 4,
            label: '农、林、牧、渔、水利业生产人员'
        },
        {
            value: 5,
            label: '生产、运输设备操作人员及有关人员'
        },
        {
            value: 6,
            label: '军人'
        }, {
            value: 7,
            label: '不便分类的其他从业人员'
        },
        {
            value: 8,
            label: '学生'
        },
        {
            value: 9,
            label: '无职业'
        }
    ])
    //健康信息选项数据
    const allergyHistoryData = reactive([
        {
            name: '无',
            checked: false,
        },
        {

            name: '青霉素',
            checked: false,
        },
        {

            name: '磺胺',
            checked: false,
        },
        {
            name: '链霉素',
            checked: false,
        },
        {
            name: '其他',
            checked: false,
        },
    ])
    const exposureHistoryData = reactive([
        {
            name: '无',
            checked: false
        },
        {
            name: '化学品 ',
            checked: false
        },
        {
            name: '毒物',
            checked: false
        },
        {
            name: '射线',
            checked: false
        }
    ])
    const pastHistoryData = reactive([
        {
            name: '无',
            checked: false
        },
        {
            name: '疾病',
            checked: false
        },
        {
            name: '手术',
            checked: false
        },
        {
            name: '外伤',
            checked: false
        },
        {
            name: '输血',
            checked: false
        },
    ])
    const geneticHistoryData = reactive([
        {
            name: '无',
            checked: false
        },
        {
            name: '有',
            checked: false
        }
    ])
    const familyHistoryData = reactive([
        {
            name: '无',
            checked: false
        },
        {
            name: '有',
            checked: false
        }
    ])
    const disabilityHistoryData = reactive([
        {
            name: '无',
            checked: false
        },
        {
            name: '视力残疾',
            checked: false
        },
        {
            name: '听力残疾',
            checked: false
        },
        {
            name: '语言残疾',
            checked: false
        },
        {
            name: '肢体残疾',
            checked: false
        },
        {
            name: '智力残疾',
            checked: false
        },
        {
            name: '精神残疾',
            checked: false
        },
        {
            name: '语言表达障碍',
            checked: false
        },
        {
            name: '阅读障碍',
            checked: false
        },
        {
            name: '视空间障碍',
            checked: false
        },
        {
            name: '书写困难',
            checked: false
        },
        {
            name: '学习障碍',
            checked: false
        },
        {
            name: '情绪障碍',
            checked: false
        },
        {
            name: '行为障碍',
            checked: false
        },
        {
            name: '其他残疾',
            checked: false
        },
    ])
    //返回上一级
    const goBack = () => {
        store.commit('updateTitle', '患者信息')
        router.push('patientManage')
    }
    //修改复选框数据data中的checkd值
    const getChecked = (healthFormValue: any, ArrayData: any, whichData: string) => {
        ArrayData = JSON.parse(JSON.stringify(ArrayData))
        for (let i = 0; i < ArrayData.length; i++) {
            for (let j = 0; j < healthFormValue.length; j++) {
                if (ArrayData[i].name == healthFormValue[j]) {
                    ArrayData[i].checked = true
                }
            }
        }
        healthForm[whichData] = ArrayData
    }
    //添加患者
    const addPatinentFun = (value: any) :undefined |boolean=> {
        if (!checkIdCard(value.idCard)) {
            ElMessage({
                type: 'warning',
                message: '请输入正确的身份证号'
            })
            return false
        } else {
            addPatient(value).then(res => {
                if (res.data.code == 4000) {
                    ElMessage({
                        message: res.data.message,
                        type: 'error'
                    })
                    clear()
                    return false
                } else {
                    flag.value = true //需要放到新增患者的成功回调函数中
                    closeTextArea() //需要放到新增患者的成功回调函数中
                    clear() //需要放到新增患者的成功回调函数中
                    store.commit('updateTitle', '患者信息')
                    ElMessage({
                        message: '新增患者成功',
                        type: 'success'
                    })
                    setTimeout(() => {
                        router.push('patientManage')
                    }, 500)
                }
            })
        }
    }
    //保存
    let sendParams = reactive({})
    //修改最终的提交数据
    const setFinalData = ()  => {
        getChecked(healthForm.allergyHistory, allergyHistoryData, 'allergyHistory')
        getChecked(healthForm.exposureHistory, exposureHistoryData, 'exposureHistory')
        getChecked(healthForm.pastHistory, pastHistoryData, 'pastHistory')
        getChecked(healthForm.disabilityHistory, disabilityHistoryData, 'disabilityHistory')
        getChecked(healthForm.familyHistory, familyHistoryData, 'familyHistory')
        getChecked(healthForm.geneticHistory, geneticHistoryData, 'geneticHistory')
        //追加其他内容
        healthForm.allergyHistory.push({ remark: allergyRemark.value })
        healthForm.disabilityHistory.push({ remark: disabilityRemark.value })
        healthForm.familyHistory.push({ remark: familyRemark.value })
        healthForm.geneticHistory.push({ remark: geneticRemark.value })
        //将健康数据转为json格式
        healthForm.allergyHistory = JSON.stringify(healthForm.allergyHistory) as any
        healthForm.exposureHistory = JSON.stringify(healthForm.exposureHistory) as any
        healthForm.pastHistory = JSON.stringify(healthForm.pastHistory) as any
        healthForm.disabilityHistory = JSON.stringify(healthForm.disabilityHistory) as any
        healthForm.familyHistory = JSON.stringify(healthForm.familyHistory) as any
        healthForm.geneticHistory = JSON.stringify(healthForm.geneticHistory) as any
        sendParams = Object.assign(form, healthForm)
    }
    const save = () :undefined | boolean => {
        setFinalData()
        if ((useCheckEmpty(form))) {        //判断必选项是否录入
            addPatinentFun(sendParams)
        } else {
            flag.value = true
            return false
        }
    }
    //清空数据
    const clear = () => {
        form.patientName = '';
        form.phone = '';
        form.idCard = '';
        form.gender = '';
        form.birth = '';
        form.education = '';
        form.ethnicGroup = '';
        form.bloodType = '';
        form.clinicNumber = '';
        form.maritalStatus = '';
        form.occupation = '';
        form.hospitalId = ''
        healthForm.allergyHistory = [];
        healthForm.exposureHistory = [];
        healthForm.pastHistory = [];
        healthForm.familyHistory = [];
        healthForm.geneticHistory = [],
        healthForm.disabilityHistory = [],
        healthForm.remark = ''
    }
    //取消
    const cancel = ()=> {
        flag.value = true
        clear()
        closeTextArea()
    }
    //关闭所有文本框
    const closeTextArea = ()  => {
        familyHistoryFlag.value = false
        allergyHistoryFlag.value = false
        disabilityHistoryFlag.value = false
        geneticHistoryFlag.value = false
    }
    //患者基本信息数据
    const form = reactive({
        patientName: '',
        phone: '',
        idCard: '',
        gender: '',
        birth: '',
        education: '',
        ethnicGroup: '',
        bloodType: '',
        clinicNumber: '',
        maritalStatus: '',
        occupation: '',
        hospitalId: ''
    })
    //患者健康信息数据
    const healthForm :any= reactive({
        allergyHistory: [],
        exposureHistory: [],
        pastHistory: [],
        familyHistory: [],
        geneticHistory: [],
        disabilityHistory: [],
        remark: ''
    })
    //过敏史其他中的数据
    const allergyRemark = ref("")
    const allergyHistoryFlag = ref(false)
    //残疾情况其他中的数据
    const disabilityRemark = ref("")
    const disabilityHistoryFlag = ref(false)
    //过敏史与残疾史复选框改变
    const checkChange=()  => {
        console.log(healthForm.allergyHistory)
        // 判断是否需要出额外文本框
        if (healthForm.allergyHistory.includes('其他')) {
            allergyHistoryFlag.value = true
        } else {
            allergyHistoryFlag.value = false
            allergyRemark.value = ''
        }
        if (healthForm.disabilityHistory.includes('其他残疾')) {
            disabilityHistoryFlag.value = true
        } else {
            disabilityHistoryFlag.value = false
            disabilityRemark.value = ''
        }
    }
    //选择家族史中的有选项
    const familyRemark = ref("")
    const familyHistoryFlag = ref(false)
    //选择遗传病史中的有选项
    const geneticRemark = ref("")
    const geneticHistoryFlag = ref(false)
    //家族史与遗传病史单选框改变
    const radioChange = () => {
        if (healthForm.familyHistory.includes('有')) {
            familyHistoryFlag.value = true
        } else {
            familyHistoryFlag.value = false
            familyRemark.value = ""
        }
        if (healthForm.geneticHistory.includes('有')) {
            geneticHistoryFlag.value = true
        } else {
            geneticHistoryFlag.value = false
            geneticRemark.value = ""
        }
    }
    //过敏史的无与其他选项的禁用
    const flag = ref(false)
    const isAllergyItemDisabled = computed(() => (item: any) => {
        if (flag.value === true) {
            return false
        } else if (item.name === '无') {
            //如何选择了其他，就禁用无
            return healthForm.allergyHistory.length > 0 && !healthForm.allergyHistory.includes('无');
        } else {
            // 如果选择了 "无"，则禁用其他项  
            return healthForm.allergyHistory.includes('无');
        }
    });
    //暴露史的无与其他选项的禁用
    const isExposureItemDisabled = computed(() => (item: any) => {
        if (flag.value === true) {
            return false
        } else if (item.name === '无') {
            //如何选择了其他，就禁用无
            return healthForm.exposureHistory.length > 0 && !healthForm.exposureHistory.includes('无');
        } else {
            // 如果选择了 "无"，则禁用其他项  
            return healthForm.exposureHistory.includes('无');
        }
    })
    //既往史的无与其他选项的禁用
    const isPastItemDisabled = computed(() => (item: any) => {
        if (flag.value === true) {
            return false
        } else if (item.name === '无') {
            //如何选择了其他，就禁用无
            return healthForm.pastHistory.length > 0 && !healthForm.pastHistory.includes('无');
        } else {
            // 如果选择了 "无"，则禁用其他项  
            return healthForm.pastHistory.includes('无');
        }
    })
    //残疾情况的无与其他选项的禁用
    const isDisabilityItemDisabled = computed(() => (item: any) => {
        if (flag.value === true) {
            return false
        } else if (item.name === '无') {
            //如何选择了其他，就禁用无
            return healthForm.disabilityHistory.length > 0 && !healthForm.disabilityHistory.includes('无');
        } else {
            // 如果选择了 "无"，则禁用其他项  
            return healthForm.disabilityHistory.includes('无');
        }
    })
    //获取医院列表数据
    const hospitalData = ref<IHospitalResultType[]>([])
    onMounted(async() => {
        store.commit('updateTitle', '新增患者')
        const res:IHospitalResponse= await getHospitalList()
        hospitalData.value = res.data.result
    })
</script>
<style scoped lang="scss">
    .demo-form-inline .el-input {
        --el-input-width: 160px;
    }

    .demo-form-inline .el-select {
        --el-select-width: 160px;
    }

    .container {
        .card-container {
            padding: 10px;
            background-color: white;
            border-radius: 5px;
        }

        .tab {
            margin-bottom: 10px;
            border-left: 3px solid rgb(8, 79, 222);
            padding-left: 20px;
            
            
        }

        .btn-container {
            display: flex;
            justify-content: flex-end;
        }

        .bottom-btn {
            text-align: center;

            .save {
                background-color: rgb(22, 155, 213);
                color: white;
            }
        }
        .random{
            color: #3156f5;
            cursor: pointer;
        }
    }
</style>